﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace iStudio.Engine //not in utils namespace for availability
{
    public static class Extensions
    {
        public static unsafe byte[] ToByteArray(this float[] array)
        {
            if (array == null)
                throw new ArgumentNullException("array");
            byte[] result = new byte[array.Length * 4];
            fixed (byte* ptrresult = &result[0])
            fixed (float* ptrfarr = &array[0])
            {
                byte* ppresult = ptrresult;
                byte* ptrarr = (byte*)((void*)ptrfarr);
                for (int i = 0; i < result.Length; i++)
                {
                    *(ppresult++) = *(ptrarr++);
                }
            }

            return result;
        }

        public static unsafe void CopyToFloatArray(this byte[] array, float[] floatArray, int offset, int count)
        {
            float[] buffer = floatArray;
            byte[] byteBuffer = array; 

            fixed (float* pbuffer = &buffer[0])
            fixed (byte* pbytebuffer = &byteBuffer[0])
            {
                float* ppbuffer = pbuffer + offset;
                float* ppbytebuffer = (float*)((void*)pbytebuffer);

                for (int i = 0; i < count; i++)
                {
                    *(ppbuffer++) = *(ppbytebuffer++);
                }
            }
        }

        public static T[] CheckForSize<T>(this T[] source, int size)
        {
            if (source == null)
                return new T[size];
            else if (source.Length < size)
                return new T[size];
            else
                return source;
        }
    }
}
